package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.profix}")
    String profix;

    @Value("${file.oss.web-site}")
    String webSite;


    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //参数校验
        if (file.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //上传到oss
        String fileId = null;
        try {
            //uuid生成随机名称
            String fileName = UUID.randomUUID().toString().replace("-", "");
            //获取原始名称
            String originalFilename = file.getOriginalFilename();
            String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));

            fileId = fileStorageService.store(profix, fileName + postfix, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl file upload error:{}", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }

        //在wmMaterial中保存数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(fileId);
        save(wmMaterial);

        wmMaterial.setUrl(webSite + fileId);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();

        //查询列表
        //判断是否是收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {

            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());

        }

        //当前用户登录的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询用户素材

        queryWrapper.eq(WmMaterial::getUserId, user.getId());


        //根据时间倒序
       queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //分页
        IPage<WmMaterial> paramQuery = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> pageResult = page(paramQuery, queryWrapper);

        //显示图片
        List<WmMaterial> wmMaterials = pageResult.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        }

        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }


    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        //参数校验
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //判断是否被引用
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);

        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }

        //删除图片地址
        fileStorageService.delete(wmMaterial.getUrl());

        //删除素材库
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //参数校验
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //得到wmUser的id
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //修改  条件（getIsCollection==type  WmMaterial.id==id  WmMaterial.userId==wmUser.id  ）
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,uid)
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
